<?
if($_SESSION['sid']!=1) {exit("<script>window.location='dlogin.html'</script>");}
ob_start();
include("common/header.html");
include("common/left.html");
$s = new SoapClient(null,array(
        "location" => "http://localhost/open/openService/pft_insideMX.php",
        "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
);
$out_html=ob_get_contents();
ob_end_clean();

include("common/page.php");
//$_a->authVerify();

$dtypeT=array(0=>"购买产品",1=>"撤改订单",3=>"账户资金变化",4=>"供应商授信余额",5=>"利润",6=>"提现冻结",7=>"电子凭证费",8=>"短信息费",9=>"银行交易手续费",10=>"凭证费",11=>"供应商信用额度变化 ",12=>"取消提现",13=>"拒绝提现",14=>"退款手续费",15=>"押金",16=>"充值返现",17=>"撤销撤改");
$ptypeT=array(0=>"账号资金",1=>"支付宝",2=>"供应商可用资金",3=>"供应授信额度设置",4=>"财付通",5=>'银联',6=>'环迅');
$r=array();
$pageSize=$_REQUEST['pageSize']?$_REQUEST["pageSize"]:10;
$currentPage=$_REQUEST["currentPage"]?$_REQUEST["currentPage"]:1;
$offset=($currentPage-1)*$pageSize;
if($_REQUEST['act']=="Export")
{
	$offset=0;$pageSize=99999;
	// $offset=0;$pageSize=9;
}

$select_only_one = false;
$where1=$where2="where 1=1";
$where1.=" and dmoney>0 ";
$dname=$_REQUEST['dname'];

if($beginDate=mysql_real_escape_string($_REQUEST['beginDate'])){
	$where1.=" and rectime>='$beginDate 00:00:00'";
	$where2.=" and rectime>='$beginDate 00:00:00'";
}
if($endDate=mysql_real_escape_string($_REQUEST['endDate'])){
	$where1.=" and rectime<='$endDate 23:59:59'";
	$where2.=" and rectime<='$endDate 23:59:59'";
}
if($_REQUEST['daction']==="0"){
	$daction=$_REQUEST['daction'];
	$where1.=" and daction=$daction";
}
//退票的收入算在2里面
if($_REQUEST['daction']==="1"){
	$where1.=" and daction in (1,2)";
}
if($_REQUEST['dtype']==7){
    $where1.=" and dtype in(7,8,9,10)";
    $where2="where -1=1";
}elseif($_REQUEST['dtype']==="6"){
    $where1.=" and dtype in (6,12)";
    $where2="where -1=1";
}
elseif($_REQUEST['dtype']||$_REQUEST['dtype']==="0"){
	$where1.=" and dtype=".$_REQUEST['dtype'];
	$where2="where -1=1";
}
if($_REQUEST['account']=="pft" || !$_REQUEST['account']){
    $_REQUEST['account'] = 'pft';
	$where1.=" and ptype in (0,1,4,5,6,16)";
	$where2="where -1=1";
}
if($_REQUEST['account']=="credit"){
	$where1.=" and ptype=2";
	$where2="where -1=1";
}
if($_REQUEST['account']=="creditSet"){
	$where1.=" and ptype=3";
	$where2="where -1=1";
}
if($_REQUEST['account']=="tenpay"){
	$where1.=" and ptype in (1,4,5,6)";
	$where2="where -1=1";
}
if($_REQUEST['account']=="unipay"){
    $where1.=" and ptype=5";
    $where2="where -1=1";
}
if($_REQUEST['account']=="ips_pay"){
    $where1.=" and ptype=6";
    $where2="where -1=1";
}
if($_REQUEST['account']=="alipay"){
	$where1="where -1=1";
    //$where2="where 1=1 ";
    unset($_REQUEST['dtype']);
}
if($_REQUEST['account']=="all"){
    $where1.=" and 1=1";
    $where2.=" and 1=1";
}
if($dname&&is_numeric($dname)&&strlen($dname)==6){
    $str="select id from pft_member where account='$dname'";
    $GLOBALS['le']->query($str);
    while($row=$GLOBALS['le']->fetch_assoc()){
        $ids[]=$row['id'];
    }
    if(count($ids)!=0){
        $ids=implode(",",$ids);
        $where1.=" and fid in ($ids)";
        $where2.=" and fid in ($ids)";
    }else{
        $where1.=" and 1<>1";
        $where2.=" and 1<>1";
    }
}elseif(strlen($dname+0)==11){
    $str="select id from pft_member where mobile='$dname' limit 1";
    $GLOBALS['le']->query($str);
    $row=$GLOBALS['le']->fetch_assoc();
    if($row['id']){
        $where1.=" and fid in ({$row['id']})";
        $where2.=" and fid in ({$row['id']})";
    }
}elseif($dname=mysql_real_escape_string(trim($_REQUEST['dname']))){
    if(!is_numeric($dname)){
        $ids=array();
        $str="select id from pft_member where dname like '%".$dname."%'";
        $GLOBALS['le']->query($str);
        while($row=$GLOBALS['le']->fetch_assoc()){
            $ids[]=$row['id'];
        }
        if(count($ids)!=0){
            $ids=implode(",",$ids);
            $where1.=" and fid in ($ids)";
            $where2.=" and fid in ($ids)";
        }else{
            $where1.=" and 1<>1";
            $where2.=" and 1<>1";
        }
    }else{
        $where1.=" and fid in ($dname)";// 直接输入数字根据ID来查找 2015/04/15 abc
        $where2.=" and fid in ($dname)";
        $ids = $dname;
    }

}
if($_REQUEST['orderid']){
    $where1 .= " and orderid='{$_REQUEST['orderid']}'";
    $where2 .= " and orderid='{$_REQUEST['orderid']}'";
}
if(!count($_GET)){
    $no_search_mark = 1;
    goto zzzz;
}

if($_REQUEST['account']=='alipay'){
    $str="select id,fid,money as dmoney,'' as lmoney,'' as aid,orderid,daction,rectime,dtype,-1 as ptype,ali_account from pft_member_alipay $where2 order by rectime desc,orderid desc limit $offset,$pageSize";
}elseif(($_REQUEST['account']!='alipay' && $_REQUEST['account']!=''&&$_REQUEST['account']!='all')||$_REQUEST['account']==""){
	//排序错误 只留下了 id的倒序
	$str="select id,fid,dmoney,lmoney,aid,orderid,daction,rectime,dtype,ptype,'' as ali_account,opid,memo from pft_member_journal $where1 order by id desc limit $offset,$pageSize";
}elseif($_REQUEST['account']=="all"){
    if($dname!=""||$beginDate!=""||$endDate!=""||$_REQUEST['daction']!=""||$_REQUEST['dtype']!=""||$_REQUEST['orderid']!=""){
        $str="select id,fid,dmoney,lmoney,aid,orderid,daction,rectime,dtype,ptype,'' as ali_account,memo from pft_member_journal $where1 UNION 
             (select id,fid,money as dmoney,'' as lmoney,'' as aid,orderid,daction,rectime,dtype,-1 as ptype,ali_account from pft_member_alipay $where2)
              order by rectime desc,orderid desc,id desc limit $offset,$pageSize";
    }else{
        $str="";
    }
}

if($_GET['cs']) {
    echo $str;
}
$_nSStatusT=array("0"=>"未使用","1"=>"已使用","2"=>"已过期","3"=>"已取消","4"=>"凭证码被替代","6"=>"被终端撤销</br>(已取消)","5"=>"被终端修改----(已使用)");
if($_GET['no_test'])
    $test_id = include 'module/zax/admin_report/test_id.php';
$dname_str = '';
if($str!=""){
    $GLOBALS['le']->query($str);
    while($row=$GLOBALS['le']->fetch_assoc()){
        /*过滤测试账号*/
        if($_GET['no_test']){if(in_array($row['fid'],$test_id)) continue;}
        if($row['orderid']!=''){
            if(!$UUstatus_[$row['orderid']]){
                $x = simplexml_load_string($s->Order_Globle_Search( "",'', "", "", "", "", "", "","", "",
                    "", "", $row['orderid'], "", "", "", "", "", "", "",0, 1, 0, 0, "", 0, "", 0, "","",
                    '', 0, 0, 0, ""));
                $UUstatus_[$row['orderid']] =$row['UUstatus'] =$_nSStatusT[(int)$x->Rec->UUstatus];
            }else{
                $row['UUstatus'] = $UUstatus_[$row['orderid']];
            }
        }
        if ($row['dtype']==3) {
            //提现的金额
            $dtype_3 = 1;
        }
        if ($row['dtype']==6) {
            //提现的金额
//            $dtype_6 = 1;
            if($row['daction']==0){
                $row['dtype'] = 12;
                $row['income']="<span class='income'>".$row['dmoney']/100 .'</span>';
            }else{
                $row['pay']="<span class='pay'>".$row['dmoney']/100 . '</span>';
            }
        }elseif($_REQUEST['account']=='alipay'){
            $row['pay']="<em class='red'>-".($row['dmoney']/100)."</em>";
        }else{
            if($row['daction']==0){
                $row['income']="<em class='green'>+".($row['dmoney']/100).($row['aid']?"(".$dnames[$row['aid']]."授信)</em>":"</em>");
            }else{
                $row['pay']="<em class='red'>-".($row['dmoney']/100)."</em>";
            }
        }
        if($row['dtype'] == -1){//鼓浪屿专用 不过ali_account都是空
            $row['dtypeT']="支付宝账号".$row['ali_account'];
        }
        $r[]=$row;
        $dname_str .=$row['fid'].',';
    }
}
//充值体现 平台帐户时 查询订单号
if($dtype_3 && is_array($r)){
    foreach($r as $kay=>$vall){
        $strs="select dname from pft_member where id={$vall['opid']} limit 1";
        $GLOBALS['le']->query($strs);
        $GLOBALS['le']->fetch_assoc();
        $r[$kay]['operator']=$GLOBALS['le']->f("dname");
        
        //查询淘宝交易号
        $total_fee = (float)$vall['dmoney']/100;
        //小数位补0
//        $lenth =strlen(substr($total_fee , strpos($total_fee,'.')));
//        switch($lenth){
//            case 2:
//                $total_fee = (string)$total_fee.'0';
//                break;
//            case 1:
//                $total_fee = (string)$total_fee.'.00';
//        }
        $etime = date('Y-m-d H:i:s',(strtotime($vall['rectime'])+1));
        $btime = date('Y-m-d H:i:s',(strtotime($vall['rectime'])-1));
        $sel_trade_no = "select trade_no from pft_alipay_rec  where total_fee='$total_fee' and dtime>='$btime' and  dtime<='$etime' limit 1";
        if($_GET['cs']){
            echo $sel_trade_no;
            echo "</br>";
        }

        $GLOBALS['le']->query($sel_trade_no);
        $GLOBALS['le']->fetch_assoc();
        $r[$kay]['trade_no'] = $GLOBALS['le']->f("trade_no");
    }
}
if($_GET['csj']){
    echo "<pre>";
    print_r($r);
    echo "</pre>";
    exit;
}
//当查询的是提现冻结时 判断下是否已取消
/*
if($dtype_6){
    foreach($r as $k => $v){
        if($v['income']!='' && $v['dtype']==6){
            $sel_status = "select wd_status,batchno from pft_wd_cash where fid={$v['fid']} and apply_time='{$v['rectime']}' limit 1";
            $GLOBALS['le']->query($sel_status);
            $GLOBALS['le']->fetch_assoc();
            $wd_status = $le->f('wd_status');
            $r[$k]['dtype'] = $wd_status==3 ? 12 :6;
            if($r[$k]['dtype']==12){
                $r[$k]['income'] = "<span class='green'>+".strip_tags($r[$k]['pay']).'</span>';
                $r[$k]['pay'] = '';
            }
            $r[$k]['trade_no'] = $GLOBALS['le']->f('batchno');
        }
    }
}
*/
/*
 * 处理账户余额显示错误的问题 原因是数据库同时对一条数据进行处理 2015-04-17 zax
 * 以最后一个行的余额为基准 array_pop 对其他行的余额进行加减运算来得到正确的余额 不使用从数据库里查出来的值
 * 先倒序一次 方便foreach 再倒回来
*/

/* 2015-05-10 zax
 * 为了绝对防止金额错误 在本页记录之前再取一条来比对 看看金额/时间是否一样
 * 如果不一样 表示不是并发 可以正常计算
 * 如果一样 则往前再取一条 直到取到不一样的为止
 * */
goto zzzz;

if(!$_GET['dtype'] && $_GET['account']=="pft" && count($r)){
    /*只查了一个帐户的情况下才进行重新计算*/
    $z_id = $r[0]['fid'];
    foreach ($r as $v) {
        if($v['fid']!=$z_id)
            goto zzzz;
    }
    /*
   2015-05-10 zax
   最残酷的情况 只查一条
   传三条记录进去比较
   中间的一条如果和头尾的两条记录的时间和初金额都不一样 则被认定为是正确的数据
   注:初金额指lmoeny与dmoney计算后的结果
   */
    /* 早先版本 一下子把最后三条都传进去 但是没考虑到不足三条的情况
    $last_1 = array_pop($r);//早
    $last_2 = array_pop($r);//中
    $last_3 = array_pop($r);//晚
    $last = array($last_3,$last_2,$last_1);
    */
    $last_1 = array_pop($r);//中
    $last = array('',$last_1,'');
    function get_last_one($last){

        $str="select id,lmoney,rectime,daction,dmoney,dtype,ptype,orderid,memo
              from pft_member_journal where fid={$GLOBALS['z_id']} and dmoney>0 and
              ptype in (0,1,4) and rectime<='{$last[1]['rectime']}' and
               id<{$last[1]['id']} order by id desc limit 1";
        $GLOBALS['le']->query($str);
        $last[2]=$GLOBALS['le']->fetch_assoc();//早
        if($last[2]['daction'] == '0') $last[2]['income'] = '+'.$last[2]['dmoney']/100;
        else $last[2]['pay'] = '-'.$last[2]['dmoney']/100;

        if($last[0]!=''){//只有第一层递归会用到这个判断 之后都会存在 不需要再去取了
            $str="select id,lmoney,rectime,daction,dmoney,dtype,ptype,orderid,memo
                  from pft_member_journal where fid={$GLOBALS['z_id']} and dmoney>0 and
                  ptype in (0,1,4) and rectime>='{$last[1]['rectime']}'
                  and id>{$last[1]['id']} limit 1";
            $GLOBALS['le']->query($str);
            $last[0]=$GLOBALS['le']->fetch_assoc();//晚
            if($last[0]['daction'] == '0') $last[0]['income'] = '+'.$last[0]['dmoney']/100;
            else $last[0]['pay'] = '-'.$last[0]['dmoney']/100;
        }
        foreach ($last as $k => $v) {
            $last[$k]['zmoney'] = $last[$k]['daction'] == 0 ?
                $last[$k]['lmoney'] - $last[$k]['dmoney']: $last[$k]['lmoney'] + $last[$k]['dmoney'];
        }
        if(
            ($last[0]['rectime']==$last[1]['rectime']&& $last[0]['zmoney']==$last[1]['zmoney'] )
            ||
            ($last[2]['rectime']==$last[1]['rectime']&&$last[2]['zmoney']==$last[1]['zmoney'] )
        ){
            //递归查找到最后面一条正确金额的记录作为基准

            $new_last = array($last[1],$last[2],'');
            $new_last = get_last_one($new_last);
            $last[1] = $new_last[0];
        }
        $last[2]['lmoney'] = $last[1]['daction'] == 0 ?
            $last[1]['lmoney'] - $last[1]['dmoney']: $last[1]['lmoney'] + $last[1]['dmoney'];

        $last[0]['lmoney'] = $last[0]['daction'] == 0 ?
            $last[1]['lmoney'] + $last[0]['dmoney']: $last[1]['lmoney'] - $last[0]['dmoney'];
        return $last;
    }
    $last = get_last_one($last);
    $last_1 = $last[1];
    $last_money = $last[1]['lmoney'];
    if(count($r)){//不知道空数组会不会报错 好累 不想测试了 蛮写个判断吧
        krsort($r);
        foreach($r as $k => $v){
            $last_money = $r[$k]['lmoney'] = $v['daction'] == 0 ?
                $last_money + $v['dmoney']: $last_money - $v['dmoney'];
        }
        ksort($r);
    }
    array_push($r,$last_1);
}
zzzz:


if($_REQUEST['account']=='alipay' && is_array($r)){

    foreach($r as $k => $row){
        $sql = "select sourceT from pft_alipay_rec where out_trade_no={$row['orderid']} limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $row['sourceT'] = $GLOBALS['le']->f('sourceT');
        switch ($row['sourceT']) {
            case '0':
                $r[$k]['ptype']=1;
                break;
            case '1':
                $r[$k]['ptype']=4;
                break;
            case '2':
                $r[$k]['ptype']=5;
                break;
            default:
                $r[$k]['ptype']=1;
        }
    }
}

$dname_str = rtrim($dname_str,',');
if($dname_str!=''){
    $dnames=array();
    $str="select id,dname,account from pft_member where id in($dname_str)";
    $GLOBALS['le']->query($str);
    $dn=array();
    while($row=$GLOBALS['le']->fetch_assoc()){
        $dn[$row['id'].'_'.$row['account']]=$row['dname'];
        $dnames[$row['id']]=$row['dname'];
    }
    $ainfo=$t=array();
    foreach($dn as $key=>$d){
        $k=explode('_',$key);
        $t['id']=$k[0];
        $t['dname']=$d;
        $t['account']=$k[1];
        $ainfo[]=$t;
    }
}


if($_REQUEST['act']=="Export")
{
	$filename=date('YmdHis').'交易记录';
	$Excel[0]['member']='交易商户';
	$Excel[0]['rectime']='交易时间';
	$Excel[0]['orderid']=$_GET['dtype']==3?'交易号':'订单号';
    $Excel[0]['UUstatus'] = '订单状态';
	$Excel[0]['dtype']='交易内容';
	$Excel[0]['ptype']='交易方式';
	$Excel[0]['pay']='收入';
    if($row['ptype']==0){
        $Excel[0]['pay_out']='支出';//2015-1-9新加 By zax
    }
	$Excel[0]['alipay']='银行账户';
	$Excel[0]['lmoney']='账户余额';
	$Excel[0]['lmoney2']='授信余额';
    if($_REQUEST['dtype']&&$_REQUEST['dtype']==3&&$_REQUEST['account']&&$_REQUEST['account']=="pft"){
        $Excel[0]['operator']='操作员';
    }
    $Excel[0]['memo']='备注';
	$i=1;
	foreach($r as $lid=>$row){
		$n++;
        // if(strpos($dnames[$row['fid']],'测试')!==false)continue;
		$Excel[$n]['member']=$dnames[$row['fid']];
		$Excel[$n]['rectime']=$row['rectime'];
		$Excel[$n]['orderid']=$row['orderid'] ? $row['orderid']:(string)$row['trade_no'];
        $Excel[$n]['UUstatus'] = $row['UUstatus'];
		$Excel[$n]['dtype']=$dtypeT[$row['dtype']] ? $dtypeT[$row['dtype']]:$row['dtypeT'];
		$Excel[$n]['ptype']=$ptypeT[$row['ptype']];
        $Excel[$n]['pay']=strip_tags($row['income']);
        $Excel[$n]['pay_out'] = ltrim(strip_tags($row['pay']),'-');
        $Excel[$n]['alipay']=$row['alipay'];
        $Excel[$n]['lmoney']=($row['ptype']==0||$row['ptype']==1||$row['ptype']==4||$row['ptype']==5||$row['ptype']==6)?$row['lmoney']/100:"";
		$Excel[$n]['lmoney2']=($row['ptype']==2||$row['ptype']==3)?($row['lmoney']/100)."(".$dnames[$row['aid']].")":"";
        if($_REQUEST['dtype']&&$_REQUEST['dtype']==3&&$_REQUEST['account']&&$_REQUEST['account']=="pft"){
            $Excel[$n]['operator']=$row['operator'];
        }
        $Excel[$n]['memo']=$row['memo'];
	}
	$xls = new SimpleExcel('UTF-8', true,'orderList');
    $xls->addArray($Excel);
    $xls->generateXML($filename);
    @$GLOBALS['le']->close();
	exit;
}
if($str==""){
    $r[]="";
}

if(!$no_search_mark)

    if($_REQUEST['account']=='alipay'){
        $str="select count(*) as total from pft_member_alipay $where2";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $count=$GLOBALS['le']->f("total");
    }elseif(($_REQUEST['account']!='alipay'&&$_REQUEST['account']!=""&&$_REQUEST['account']!='all')||$_REQUEST['account']==""){
        $str="select count(*) as total from pft_member_journal $where1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $count=$GLOBALS['le']->f("total");
    }
    elseif($_REQUEST['account']=="all"){
        if($dname!=""||$beginDate!=""||$endDate!=""||$_REQUEST['daction']!=""
            ||$_REQUEST['dtype']!=""||$_REQUEST['orderid']!=""){
            $str1="select count(*) as total1 from pft_member_alipay $where2";
            $GLOBALS['le']->query($str1);
            $GLOBALS['le']->fetch_assoc();
            $count1=$GLOBALS['le']->f("total1");
            $str2="select count(*) as total2 from pft_member_journal $where1";
            $GLOBALS['le']->query($str2);
            $GLOBALS['le']->fetch_assoc();
            $count2=$GLOBALS['le']->f("total2");
            $count=$count1+$count2;
        }
    }
else{
    $count = 0;
}
// $count=$count1+$count2;
// var_dump($count);
$currentPage=$_REQUEST['currentPage']?abs($_REQUEST['currentPage']):1;
$pageSize=$_REQUEST['pageSize']?abs($_REQUEST['pageSize']):10;
$offset=($currentPage-1)*$pageSize;
echo $out_html;
include("tpl/accountTrecord.tpl");
include("common/footer.html");
?>